/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Thresholds;
import it.polimi.games.epkb.entityClasses.ThresholdsPK;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.epkb.entityClasses.Component;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ThresholdsJpaController implements Serializable {

    public ThresholdsJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }
    public ThresholdsJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Thresholds thresholds) throws PreexistingEntityException, Exception {
        if (thresholds.getThresholdsPK() == null) {
            thresholds.setThresholdsPK(new ThresholdsPK());
        }
        thresholds.getThresholdsPK().setIdComponent(thresholds.getComponent().getId());
        thresholds.getThresholdsPK().setIdGPIKPI(thresholds.getGpiKpi().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            GpiKpi gpiKpi = thresholds.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi = em.getReference(gpiKpi.getClass(), gpiKpi.getId());
                thresholds.setGpiKpi(gpiKpi);
            }
            Component component = thresholds.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                thresholds.setComponent(component);
            }
            em.persist(thresholds);
            if (gpiKpi != null) {
                gpiKpi.getThresholdsCollection().add(thresholds);
                gpiKpi = em.merge(gpiKpi);
            }
            if (component != null) {
                component.getThresholdsCollection().add(thresholds);
                component = em.merge(component);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findThresholds(thresholds.getThresholdsPK()) != null) {
                throw new PreexistingEntityException("Thresholds " + thresholds + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Thresholds thresholds) throws NonexistentEntityException, Exception {
        thresholds.getThresholdsPK().setIdComponent(thresholds.getComponent().getId());
        thresholds.getThresholdsPK().setIdGPIKPI(thresholds.getGpiKpi().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Thresholds persistentThresholds = em.find(Thresholds.class, thresholds.getThresholdsPK());
            GpiKpi gpiKpiOld = persistentThresholds.getGpiKpi();
            GpiKpi gpiKpiNew = thresholds.getGpiKpi();
            Component componentOld = persistentThresholds.getComponent();
            Component componentNew = thresholds.getComponent();
            if (gpiKpiNew != null) {
                gpiKpiNew = em.getReference(gpiKpiNew.getClass(), gpiKpiNew.getId());
                thresholds.setGpiKpi(gpiKpiNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                thresholds.setComponent(componentNew);
            }
            thresholds = em.merge(thresholds);
            if (gpiKpiOld != null && !gpiKpiOld.equals(gpiKpiNew)) {
                gpiKpiOld.getThresholdsCollection().remove(thresholds);
                gpiKpiOld = em.merge(gpiKpiOld);
            }
            if (gpiKpiNew != null && !gpiKpiNew.equals(gpiKpiOld)) {
                gpiKpiNew.getThresholdsCollection().add(thresholds);
                gpiKpiNew = em.merge(gpiKpiNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.getThresholdsCollection().remove(thresholds);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.getThresholdsCollection().add(thresholds);
                componentNew = em.merge(componentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                ThresholdsPK id = thresholds.getThresholdsPK();
                if (findThresholds(id) == null) {
                    throw new NonexistentEntityException("The thresholds with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(ThresholdsPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Thresholds thresholds;
            try {
                thresholds = em.getReference(Thresholds.class, id);
                thresholds.getThresholdsPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The thresholds with id " + id + " no longer exists.", enfe);
            }
            GpiKpi gpiKpi = thresholds.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi.getThresholdsCollection().remove(thresholds);
                gpiKpi = em.merge(gpiKpi);
            }
            Component component = thresholds.getComponent();
            if (component != null) {
                component.getThresholdsCollection().remove(thresholds);
                component = em.merge(component);
            }
            em.remove(thresholds);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Thresholds> findThresholdsEntities() {
        return findThresholdsEntities(true, -1, -1);
    }

    public List<Thresholds> findThresholdsEntities(int maxResults, int firstResult) {
        return findThresholdsEntities(false, maxResults, firstResult);
    }

    private List<Thresholds> findThresholdsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Thresholds.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Thresholds findThresholds(ThresholdsPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Thresholds.class, id);
        } finally {
            em.close();
        }
    }

    public int getThresholdsCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Thresholds> rt = cq.from(Thresholds.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
